package com.jsgt.greekfire.ui.main.updatedialog

import android.Manifest
import android.app.Notification
import android.app.PendingIntent
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.Window
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import androidx.core.content.FileProvider
import androidx.lifecycle.Observer
import com.fhx.core.AppConfig
import com.fhx.core.base.BaseDialogFragment
import com.fhx.core.utils.*
import com.ftd.livepermissions.LivePermissions
import com.ftd.livepermissions.PermissionResult
import com.jsgt.greekfire.App
import com.jsgt.greekfire.BuildConfig
import com.jsgt.greekfire.R
import com.jsgt.greekfire.bean.UpdateBean
import com.jsgt.greekfire.common.util.NotificationUtil
import java.io.File


/**
 * APP更新窗口
 * author fhx
 * create time 2020/5/10 20:36
 **/
class UpdateDialogFragment : BaseDialogFragment() {
    override fun getLayoutId(): Int = R.layout.fragment_update

    override fun getDialogStyle(): Int = R.style.DialogTheme
//    val appName = "GFC.apk"
    val appName = "atr" + "_v" + BuildConfig.VERSION_NAME + ".apk"
    var downLoadSuccess = false//本次是否下载成功
    override fun canCancel(): Boolean = false
    var notificationUtil: NotificationUtil? = null
    override fun setWindowAttributes(window: Window?) {
//        val params = window?.attributes
//        params?.width =
//            ScreenUtil.getScreenWidth(mContext!!) - ScreenUtil.dip2px(context!!, 80f).toInt()
//        params?.height = ScreenUtil.getScreenHeight(mContext!!) / 2
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        dialog?.setOnKeyListener(object : DialogInterface.OnKeyListener {
            override fun onKey(dialog: DialogInterface?, keyCode: Int, event: KeyEvent?): Boolean {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    return true
                }
                return false
            }
        })
        val updateBean = requireArguments().getParcelable<UpdateBean>("bean")
        val updateVersion = findViewById(R.id.update_version) as TextView
        val contentTv = findViewById(R.id.content_tv) as TextView
        val updateDelete = findViewById(R.id.update_delete) as ImageView

        updateVersion.text = "v" + updateBean!!.Android!!.version
        contentTv.text = updateBean.Android!!.content
        val progressbar = findViewById(R.id.progressbar) as ProgressBar
        val progressTv = findViewById(R.id.progress_tv) as TextView
        val updateTv = findViewById(R.id.update_tv) as TextView

        updateDelete.setOnClickListener {
            dialog?.dismiss()
        }
        updateTv.setOnClickListener {
            val file = DownloadUtil.get()!!.getDownLoadFile(AppConfig.APK_PATH, appName)
            if (downLoadSuccess && file.exists()) {
                //刚刚下载过没安装的可以再次安装
                SystemUtil.installApk(file.absolutePath)
            } else {
                if (NetworkUtil.isNetworkAvailable()) {
                    LivePermissions(this).request(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                    ).observe(requireActivity(), Observer {
                        when (it) {
                            is PermissionResult.Grant -> {
                                notificationUtil = NotificationUtil(App.context)
                                updateTv.visibility = View.GONE
                                progressbar.visibility = View.VISIBLE
                                DownloadUtil.get()!!.download(
                                    updateBean.Android!!.url!!,
                                    AppConfig.APK_PATH,
                                    appName,
                                    object : DownloadUtil.OnDownloadListener {
                                        override fun onDownloadSuccess(path: String) {
                                            downLoadSuccess = true
                                            activity?.runOnUiThread {
                                                updateTv.visibility = View.VISIBLE
                                                updateTv.text = "立即安装"
                                                progressbar.progress = 0
                                                progressbar.visibility = View.GONE
                                                progressTv.text = ""
                                                updateOnSuccessNotification()
                                                SystemUtil.installApk(path)
                                            }
                                        }

                                        override fun onDownloading(progress: Int) {
                                            activity?.runOnUiThread {
                                                progressbar.progress = progress
                                                progressTv.text = "$progress%"
                                                //这里不发通知，有点卡界面
                                                /*notificationUtil?.sendNotification(
                                                    "版本升级",
                                                    "下载进度:$progress%"
                                                )*/
                                            }
                                        }

                                        override fun onDownloadFailed() {
                                            activity?.runOnUiThread {
                                                updateTv.visibility = View.VISIBLE
                                                progressbar.visibility = View.GONE
                                            }
                                        }
                                    })
                            }
                            is PermissionResult.Rationale -> {
                                ToastUtils.show(requireActivity(), "请打开文件存储权限后重试")
                            }
                            is PermissionResult.Deny -> {
                                ToastUtils.show(requireActivity(), "权限拒绝")
                            }
                        }
                    })
                } else {
                    ToastUtils.showNetUnAvailableToast()
                }
            }
        }
    }

    /**
     * 更新通知栏为下载完成状态
     */
    private fun updateOnSuccessNotification() {
        run {
            //更新通知栏
            var intent: Intent? = null
            val file: File = DownloadUtil.get()!!.getDownLoadFile(AppConfig.APK_PATH, appName)
            if (file.exists()) {
                intent = Intent()
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                intent.action = Intent.ACTION_VIEW
                val context: Context = App.context
                var uri: Uri? = null
                uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                    FileProvider.getUriForFile(
                        context,
                        context.packageName + ".fileprovider", file
                    )
                } else {
                    Uri.fromFile(file)
                }
                intent.setDataAndType(uri, "application/vnd.android.package-archive")
            }
            if (null != intent) {
                val contentIntent =
                    PendingIntent.getActivity(App.context, 0, intent, 0)
                val notification: Notification =
                    notificationUtil?.getNotification("版本升级", "下载已完成，点击安装")!!
                notification.contentIntent = contentIntent
                notificationUtil?.getNotificationManager()!!
                    .notify(NotificationUtil.downloadId, notification)
            }
        }
    }
}